package com.xiaoxi.common.response;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoxi.common.constant.enumeration.statuscode.ParentEnum;
import com.xiaoxi.common.exception.BMSException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Map;

/**
 * @Author xiaoxi
 * @ProjectName springcloudbms
 * @PackageName common.response
 * @ClassName ApiResponse
 * @Description TODO
 * @Date 2023/1/31 10:34
 * @Version 1.0
 */
@Data
@Slf4j
public class ApiResponse implements Serializable {

    private String code;
    private String message;
    private Object data;

    /**
     * 通过枚举类 返回响应内容
     *
     * @param parentEnum 1 --> N
     * @return
     */
    public static ApiResponse ofEnum(ParentEnum parentEnum) {
        ApiResponse apiResponse = new ApiResponse();
        Map<String, String> enumData = parentEnum.format();
        apiResponse.setCode(enumData.get("code"));
        apiResponse.setMessage(enumData.get("message"));
        apiResponse.setData(null);
        return apiResponse;
    }

    /**
     * 通过异常类 返回响应内容
     *
     * @param bmsException 1 --> N
     * @return
     */
    public static ApiResponse ofException(BMSException bmsException) {
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.setCode(bmsException.getCode());
        apiResponse.setMessage(bmsException.getMessage());
        apiResponse.setData(null);
        return apiResponse;
    }

    /**
     * 通过自定义信息 返回响应内容
     *
     * @param code
     * @param message
     * @return
     */
    public static ApiResponse ofMessage(String code, String message) {
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.setCode(code);
        apiResponse.setMessage(message);
        apiResponse.setData(null);
        return apiResponse;
    }

    /**
     * 成功 不带 返回数据
     *
     * @return
     */
    public static ApiResponse ofSuccess() {
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.setCode("200");
        apiResponse.setMessage("成功");
        apiResponse.setData(null);
        return apiResponse;
    }

    /**
     * 成功 带 返回数据
     *
     * @param data 待返回数据
     * @return
     */
    public static ApiResponse ofSuccess(Object data) {
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.setCode("200");
        apiResponse.setMessage("成功");
        apiResponse.setData(data);
        return apiResponse;
    }

    /**
     * 将 apiResponse 转 json
     *
     * @param apiResponse
     * @return
     */
    public static String apiResponseToJson(ApiResponse apiResponse) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(apiResponse);
        } catch (JsonProcessingException e) {
            log.error("jackJson 转化失败 ： {}", e.getMessage());
            return null;
        }
    }

}
